package com.ly.web.controller.king;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingDocTypeEntity;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.king.BaseChildBo;
import com.ly.heart.domain.king.base.DocTypeBo;
import com.ly.heart.domain.king.base.BaseModelBo;
import com.ly.heart.domain.request.KingBaseRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseError;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingDocTypeService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 23:34 2024-07-05
 * @return
 */
@Api ( value = "DocTypeRemote", tags = "推基础数据-单据类型" )
@RestController
@RequestMapping ( "/heart/DocTypeRemote" )
@Slf4j
public class DocTypeRemote {

    @Resource
    private IKingDocTypeService iKingDocTypeService;
    @Resource
    private IKingOrgService iKingOrgService;

    @ApiOperation ( "同步拉取金蝶单据类型" )
    @RequestMapping ( "pull" )
    public AjaxResult queryList () {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        //请求参数，要求为json字符串
        String jsonData = "{\"FormId\":\"" + KingConstUtil.BOS_BillType + "\",\"FieldKeys\":\"FNumber,FName,FBillFormID.FNumber,FBillCodeRuleID.FNAME,FIsDefault\",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        try {
            //调用接口
            List<List<Object>> lists = client.executeBillQuery ( jsonData );
            List<KingDocTypeEntity> docTypeEntities = new ArrayList<> ();
            for ( int i = 0; i < lists.size (); i++ ) {
                List<Object> objects = lists.get ( i );
                KingDocTypeEntity docTypeEntity = new KingDocTypeEntity ();
                //根据code查询是否已存在该结算方式
                String bizCode = ( String ) objects.get ( 0 );
                docTypeEntity.setDocCode ( bizCode );
                docTypeEntity.setTitle ( String.valueOf ( objects.get ( 1 ) ) );
                docTypeEntity.setLevel ( 2 );
                //获取父单据，绑定parentId
                String parentCode = String.valueOf ( objects.get ( 2 ) );//父单据
                //规则
                String rule = String.valueOf ( objects.get ( 3 ) );
                if ( "null".equals ( rule ) || rule == null ) {
                    rule = null;
                }
                docTypeEntity.setCodeRule ( rule );
                Boolean isDef = ( Boolean ) objects.get ( 4 );
                docTypeEntity.setIsDefault ( isDef == true ? 1 : 2 );
                docTypeEntity.setIsSend ( KingConstUtil.KING_DATA_IS_SEND_YES );
                log.info ( "docTypeEntity -- > {}", docTypeEntity );
                docTypeEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                //处理key_code
                KingDocTypeEntity parentEntity = iKingDocTypeService.getOne ( new QueryWrapper<KingDocTypeEntity> ().eq ( "doc_code", parentCode ) );
                String parentPy = "";
                if ( parentEntity == null ) {
                    parentPy = "NULL";
                } else {
                    parentPy = ChineseToPinyin.getFirstLetter ( parentEntity.getTitle () );
                }
                String docTypePy = ChineseToPinyin.getFirstLetter ( docTypeEntity.getTitle () );
                docTypeEntity.setKeyCode ( parentPy.concat ( "_" ).concat ( docTypePy ) );
                docTypeEntity.setParentCode ( parentCode );
                docTypeEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                docTypeEntity.setCreateTime ( DateUtils.getNowDate () );
                docTypeEntities.add ( docTypeEntity );
            }
            //检查有无重复
            List<String> codes = docTypeEntities.stream ()
                    .map ( KingDocTypeEntity :: getDocCode )
                    .collect ( Collectors.toList () );
            //已录入的数据集，踢掉
            List<KingDocTypeEntity> docTypeList = iKingDocTypeService.list ( new QueryWrapper<KingDocTypeEntity> ().in ( "doc_code", codes ) );
            //留下docTypeEntities多出来的就是新增的
            List<KingDocTypeEntity> diffDocTypeList = docTypeEntities.stream ()
                    .filter ( item -> ! docTypeList.stream ().map ( KingDocTypeEntity :: getDocCode )
                            .collect ( Collectors.toList () ).contains ( item.getDocCode () ) )
                    .collect ( Collectors.toList () );
            //批量插入
            iKingDocTypeService.saveBatch ( diffDocTypeList );
        } catch ( Exception e ) {
            e.printStackTrace ();
            throw new RuntimeException ( "同步单据类型失败" );
        }
        return AjaxResult.success ( "同步单据类型成功" );
    }


    /**
     * 同步所有结算方式到金蝶
     *
     * @return
     */
    @ApiOperation ( "同步发送单据类型到金蝶" )
    @RequestMapping ( "push" )
    public AjaxResult push () throws Exception {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        List<KingDocTypeEntity> list = iKingDocTypeService.list ( new QueryWrapper<KingDocTypeEntity> ().
                eq ( "dept_id", CurrentUserUtil.getCompanyId () ).
                eq ( "is_send", KingConstUtil.KING_DATA_IS_SEND_NO ).
                eq ( "level", 2 ) );
        if ( CollectionUtils.isEmpty ( list ) ) {
            return AjaxResult.error ( "暂无新数据可推！" );
        }
        batchSave ( list, client );
        submit ( list, client );
        audit ( list, client );
        return AjaxResult.success ( "推送单据类型成功。" );
    }


    /**
     * 推送结算方式
     *
     * @param list
     * @param client
     * @throws Exception
     */
    private void batchSave ( List<KingDocTypeEntity> list, K3CloudApi client ) throws Exception {
        KingBaseRequest request = new KingBaseRequest ();
        List<BaseModelBo> bos = new ArrayList<> ();
        list.forEach ( doc -> {
            DocTypeBo bo = new DocTypeBo ();
            bo.setFNumber ( doc.getDocCode () );
            bo.setFName ( doc.getTitle () );
            //处理所属父单据
            BaseChildBo childBo = new BaseChildBo ();
            childBo.setFNumber ( doc.getParentCode () );
            bo.setFBillFormID ( childBo );
            bos.add ( bo );
        } );
        request.setModel ( bos );
        String s = JSONObject.toJSONString ( request );
        String resultJson = client.batchSave ( KingConstUtil.BOS_BillType, s );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //添加成功，进行提交
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "单据类型-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 推送成功", sb );
            //修改为已推送状态
            list.forEach ( doc -> {
                iKingDocTypeService.update ( new UpdateWrapper<KingDocTypeEntity> ().
                        set ( "is_send", KingConstUtil.KING_DATA_IS_SEND_YES ).
                        set ( "update_time", DateUtils.getNowDate () ).
                        eq ( "doc_code", doc.getDocCode () ) );
            } );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "单据类型-推送失败：【" + sb + "】" );
        }
    }

    /**
     * 提交结算方式
     *
     * @param list
     * @param client
     */
    private void submit ( List<KingDocTypeEntity> list, K3CloudApi client ) throws Exception {
        DocTypeBo bo = new DocTypeBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( doc -> {
            strings.add ( doc.getDocCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.submit ( KingConstUtil.BOS_BillType, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //提交成功
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "单据类型-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.error ( "{} 提交成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "单据类型：【" + sb + "】" );
        }
    }

    /**
     * 结算方式审核
     *
     * @param list
     * @param client
     */
    private void audit ( List<KingDocTypeEntity> list, K3CloudApi client ) throws Exception {
        DocTypeBo bo = new DocTypeBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( doc -> {
            strings.add ( doc.getDocCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.audit ( KingConstUtil.BOS_BillType, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "单据类型-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 审核成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "单据类型审核失败：【" + sb + "】" );
        }
    }


}
